package org.zjx.core;

import lombok.Data;
import org.zjx.client.SocketClient;
import org.zjx.common.command.ICommand;
import org.zjx.listener.EventListener;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Queue;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentLinkedQueue;

@Data
public class GameContext {

    private Map<String, List<EventListener>> listeners;

    private SocketClient socketClient;

    private Queue<ICommand> queueData = new ConcurrentLinkedQueue<>();

    private Map<String,Object> dynamicParams = new ConcurrentHashMap<>();

    public GameContext() {
        listeners = new ConcurrentHashMap<>();
    }

    public List<String> getKeys() {
        return new ArrayList<>(listeners.keySet());
    }

    public void addListener(String name, EventListener listener) {
        listeners.computeIfAbsent(name, k -> new ArrayList<>()).add(listener);
    }

    public void removeListener(String name, EventListener listener) {
        listeners.computeIfAbsent(name, k -> new ArrayList<>()).remove(listener);
        if (listeners.get(name).isEmpty()) listeners.remove(name);
    }

    public void notifyListeners(String name, Object o) {
        if (!listeners.containsKey(name)) return;
        for (EventListener listener : listeners.computeIfAbsent(name, k -> new ArrayList<>())) {
            listener.onEvent(o);
        }
    }
}
